<?php

namespace App\Http\Controllers\Admin;

use App\Models\BranchInfo;
use App\Validate\BranchInfoValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 总分馆
 */
class BranchInfoController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new BranchInfo();
        $this->validate = new BranchInfoValidate();
    }

    /**
     * 分馆(用于下拉框选择)
     */
    public function filterList()
    {

        $condition[] = ['is_del', '=', 1];

        return $this->model->getFilterList(['id', 'is_main', 'branch_name'], $condition);
    }


    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_main string 是否总馆  1 总馆 2 分馆 
     * @param keywords string 搜索关键词
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $is_main = $this->request->is_main;
        $keywords = $this->request->keywords;

        $condition[] = ['id', '>=', 1];
        $condition[] = ['is_del', '=', 1];

        $res = $this->model->lists(null, $keywords, $is_main, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($val['intro'])));
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int id   固定传  1
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 新增
     * @param is_main string 是否总馆  1 总馆 2 分馆 
     * @param branch_name string 名称
     * @param img string 封面图片
     * @param intro string 简介 
     * @param dispark_time string 开放时间（一段文字） 
     * @param transport_line string 交通线路 
     * @param province string 省
     * @param city string 市
     * @param district string 区县
     * @param address string 详细地址
     * @param tel string 联系方式
     * @param contacts string 联系人
     * @param borrow_notice string 借阅须知
     * @param img string 
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->branch_name, 'branch_name');

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            if ($this->request->province && $this->request->city && $this->request->district) {
                $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
                if (is_string($map)) {
                    throw new  Exception($map);
                }
                $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);
            }

            $this->model->add($this->request->all());

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() ? $e->getMessage() : "新增失败");
        }
    }

    /**
     * 修改
     * @param id string id
     * @param is_main string 是否总馆  1 总馆 2 分馆 
     * @param branch_name string 名称
     * @param img string 封面图片
     * @param intro string 简介 必填
     * @param dispark_time string 开放时间（一段文字） 必填
     * @param transport_line string 交通线路 必填
     * @param province string 省
     * @param city string 市
     * @param district string 区县
     * @param address string 详细地址
     * @param tel string 联系方式
     * @param contacts string 联系人
     * @param borrow_notice string 借阅须知
     * @param img string 
     */
    public function change()
    {

        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->branch_name, 'branch_name', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(201, "参数传递失败");
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            if (
                $this->request->province &&
                $this->request->city &&
                $this->request->district &&
                ($this->request->province != $res->province ||
                    $this->request->city != $res->city ||
                    $this->request->district != $res->district ||
                    $this->request->address != $res->address
                )
            ) {
                $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
                if (is_string($map)) {
                    throw new  Exception($map);
                }
                $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);
            }

            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除 （第一条数据不支持删除）
     * @param id int 分馆id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        // $count = $this->model->where('is_del', 1)->count();
        // if ($count <= 1) {
        //     return $this->returnApi(201, "总分馆数据至少存在一条");
        // }
        if($this->request->id == 1){
            return $this->returnApi(201, "第一条数据不支持删除");
        }

        $res = $this->model->del($this->request->id);
        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }
}
